import { TODO_DEL, TODO_UPDATEBYID, TODO_ADD } from './actionType';

export const delTodoActionCreator = (id) => ({
  type: TODO_DEL,
  payload: id,
});

export const updateTodoActionCreator = (id) => {
  return {
    type: TODO_UPDATEBYID,
    payload: id,
  };
};

/*
  学习目标：模拟异步Action
*/

/* 模拟异步API的方法 */
function loadNewTodoAPI(params) {
  const newTask = '学习异步Action';
  console.log('2秒后请求成功');
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('请求成功，数据返回');
      resolve(newTask);
    }, 2000);
  });
}

// 3.1. actionCreator需要返回一个异步函数
export const addTodoActionCreator = (task) => {
  return async (dispatch) => {
    const res = await loadNewTodoAPI();
    console.log('res  ----->  ', res);
    // 3.2 使用形参中的dispatch，再次发起action
    dispatch({
      type: TODO_ADD,
      payload: res,
    });
  };
};

// 异步
// 1. return function 自动被redux-thunk拦截调用function
// 同步action
// 2. return  {type: 'xxx', payload: xxx}
